package com.itstudio.portal.filter;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itstudio.portal.entity.UserInfo;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    Long userId = null;
    @Override
    public void insertFill(MetaObject metaObject) {
        try{
            UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            userId = userInfo.getUser().getId();
        }catch (Exception e){
            userId = -1L;
        }
        this.setFieldValByName("createBy", userId, metaObject);
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try{
            UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            userId = userInfo.getUser().getId();
        }catch (Exception e){
            userId = -1L;
        }
        this.setFieldValByName("updateBy", userId, metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}